package cn.jingzhuan.fm.mvp.presenter

import cn.jingzhuan.fm.mvp.contract.FMAudioListContract
import cn.jingzhuan.fm.mvp.model.FMAudioListModel
import io.reactivex.android.schedulers.AndroidSchedulers
import javax.inject.Inject

class FMAudioListPresenter @Inject constructor(
        private val fmAudioListView: FMAudioListContract.View,
        private val fmAudioListModel: FMAudioListModel): FMAudioListContract.Presenter{

    private var isReverse = true
    private var page = 1
    private var limit = 10
    private var albumId = ""

    override fun loadMore() {
        page++
        getAudioList({
            fmAudioListView.onLoadMoreComplete()
        })

    }

    override fun refresh() {
        page = 1
        getAudioList({
            fmAudioListView.onRefresh()
        })
    }

    override fun reverse() {
        isReverse = !isReverse
        page = 1
        getAudioList({
            fmAudioListView.onRefresh()
            fmAudioListView.onReverse(isReverse)
        })
    }

    override fun getAudioList(albumId:String) {
        this.albumId = albumId
        getAudioList({})
    }

    private fun getAudioList(callback: () -> Unit?) {
        fmAudioListModel.getAudioList(page,limit,isReverse,albumId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.isSuccess) {
                        callback.invoke()
                        fmAudioListView.onDataChange(it.response)
                        if (it.response.size < limit) {
                            fmAudioListView.onNoMoreData()
                        }
                    }
                }) {
                    fmAudioListView.onDataChange(mutableListOf())
                }
    }
}
